package cn.dida.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.dida.model.OptLog;
import cn.dida.model.Sysres;
import cn.dida.model.UserSession;
import cn.dida.service.OptLogService;

import com.alibaba.fastjson.JSONObject;
/**
 * 操作日志拦截器
 * @author weiwei
 *
 */
public class OptionLogInterceptor extends HandlerInterceptorAdapter {
    private Log logger = LogFactory.getLog(getClass());

    @Autowired
    private OptLogService optLogService;
    @Autowired
    private ThreadPoolTaskExecutor executor;


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserSession userSession = (UserSession) request.getAttribute(Constants.USER_SESSION_KEY);
        Sysres Current_Res_Node = (Sysres) request.getAttribute("Current_Res_Node");

        if (!StringUtils.equals(request.getMethod(), "GET") || ServletFileUpload.isMultipartContent(request)) {
            try {
                OptLog optLog = new OptLog();
                optLog.setStaffId(userSession.getId());
                optLog.setCompanyId(userSession.getCompanyId());
                if (Current_Res_Node == null) {
                    optLog.setEvent("未知 [" + request.getMethod() + " " + request.getRequestURI() + "]");
                } else {
                    optLog.setEvent(Current_Res_Node.getName() + " [" + Current_Res_Node.getMethod() + " " + Current_Res_Node.getPath() + "]");
                }


                JSONObject detail = new JSONObject();
                detail.put("ParameterMap", request.getParameterMap());
                detail.put("RequestBody", getBodyString(request));
                optLog.setDetail(detail.toString());
                optLog.setTime(new Date().getTime());

                executor.execute(new OptLogRunnable(optLog));
            } catch (Exception e) {
                logger.error("记录操作日志异常", e);
            }
        }

    }


    class OptLogRunnable implements Runnable {
        private OptLog optLog;

        public OptLogRunnable(OptLog optLog) {
            this.optLog = optLog;
        }

        @Override
        public void run() {
            optLogService.insertLog(optLog);
        }
    }


    /**
     * 获取请求体
     *
     * @param request
     * @return
     */
    private String getBodyString(HttpServletRequest request) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String inputLine;
        String str = "";
        try {
            while ((inputLine = br.readLine()) != null) {
                str += inputLine;
            }
        } catch (IOException e) {
            System.out.println("IOException: " + e);
        } finally {
            br.close();
        }
        return str;
    }


}